import request from "@/request";
// https://github.com/RonRadtke/react-native-blob-util#readme
import RNFetchBlob from "react-native-blob-util";

import type { StateCodeMapKey } from "@/utils/websocket/stateCodeMap";

import config from "@/config";
import fso from "@/utils/FileOperate/operate";
import FileOperate from "@/utils/FileOperate";

/**
 * 发送指令
 */
export const sendCmd = (cmd: StateCodeMapKey, code: string) => {
  return request({
    url: "/api/device/api/send/cmd",
    method: "POST",
    params: {
      cmd,
      code
    }
  });
};

// TODO 生产使用 axios 发送 FormData 不知道为什么会报错
// /**
//  * 上传数据跟文件是同一个接口
//  */
// export const uploadData = (data: {
//   /** 批次id */
//   batchId: string;
//   /** 设备code */
//   deviceCode: string;
//   /** 需要上传的 json 数据 */
//   data: any;
//   /** 执行的命令码 */
//   // cmd: StateCodeMapKey;
//   cmd: string;
// }) => {
//   const formData: FormData = new FormData();
//   for (const key in data) {
//     if (Object.prototype.hasOwnProperty.call(data, key)) {
//       const value = (data as any)[key];
//       formData.append(key, value);
//     }
//   }
//   // 上传数据 file 字段为空即可
//   formData.append("file", "");

//   return request({
//     url: "/api/device/api/upload",
//     method: "POST",
//     data: formData,
//     errShowMessage: false,
//   });
// };

/**
 * 上传数据跟文件是同一个接口
 */
export const uploadData = (data: {
  /** 批次id */
  batchId: string;
  /** 设备code */
  deviceCode: string;
  /** 需要上传的 json 数据 */
  data: any;
  /** 执行的命令码 */
  // cmd: StateCodeMapKey;
  cmd: string;
}) => {
  return RNFetchBlob.fetch(
    "POST",
    config.serveUrl.getUploadUrl(),
    {
      "Content-Type": "multipart/form-data"
    },
    [
      { name: "batchId", data: data.batchId || "" },
      { name: "deviceCode", data: data.deviceCode },
      { name: "data", data: data.data },
      { name: "cmd", data: data.cmd }
    ]
    // 上传进度, 每 1000ms 触发一次
  ).uploadProgress({ interval: FileOperate.progressInterval }, (written, total) => {
    const progress = (written / total) * 100;
    fso.info(`指令回传数据进度: ${progress.toFixed(2)}%`, data);
  });
};
